﻿using System.Collections;
using UnityEngine;

public class UnitAnimator : UnitComponentBase
{
    /// <summary>
    /// 默认动画机。后期可能改为Spine或AnyPotrait
    /// </summary>
    public Animator animator => m_Animator ?? (m_Animator = entity.GetComponentInChildren<Animator>());
    private Animator m_Animator;


    /// <summary>
    /// 朝向。用于在转向时联合控制动画层的翻转
    /// </summary>
    public Vector3 direction
    {
        get => m_Direction;
        set
        {
            m_Direction = value;
            if (m_OriginalScale == null)
            {
                m_OriginalScale = animator.transform.localScale;
            }
            animator.transform.localScale = Vector3.Scale(m_OriginalScale.Value, m_Direction);
        }
    }
    private Vector3? m_OriginalScale = null;
    private Vector3 m_Direction = Vector3.one;


    protected override void OnSpawn()
    {
        animator.enabled = true;
    }

    protected override void OnDespawn()
    {
        animator.enabled = false;
    }

    protected override void OnThaw()
    {
        animator.enabled = true;
    }

    protected override void OnFreeze()
    {
        animator.enabled = false;
    }


    /// <summary>
    /// 播放动画
    /// </summary>
    public void Play(string clipName, float fade = 0f)
    {
        if (animator.HasState(0, Animator.StringToHash(clipName)) && !animator.GetCurrentAnimatorStateInfo(0).IsName(clipName))
        {
            animator.CrossFade(clipName, fade);
            animator.StartPlayback();
            animator.speed = 1;
        }
    }

    /// <summary>
    /// 目标动画是否正在播放且播放完毕
    /// </summary>
    public bool IsPlayingClipAndComplete(string clipName)
    {
        var stateInfo = animator.GetCurrentAnimatorStateInfo(0);
        return stateInfo.IsName(clipName) && stateInfo.normalizedTime >= 1.0f;
    }
}